<?php

/* 会员 member */
class MemberModel extends BaseModel
{
    var $table = 'member';
    var $prikey = 'user_id';
    var $_name = 'member';

    /* 与其它模型之间的关系 */
    var $_relation = array(
        // 一个会员拥有一个店铺，id相同
        'has_store' => array(
            'model' => 'store',       //模型的名称
            'type' => HAS_ONE,       //关系类型
            'foreign_key' => 'store_id',    //外键名
            'dependent' => true           //依赖
        ),
        'manage_mall' => array(
            'model' => 'userpriv',
            'type' => HAS_ONE,
            'foreign_key' => 'user_id',
            'ext_limit' => array('store_id' => 0),
            'dependent' => true
        ),
        // 一个会员拥有多个收货地址
        'has_address' => array(
            'model' => 'address',
            'type' => HAS_MANY,
            'foreign_key' => 'user_id',
            'dependent' => true
        ),
        // 一个用户有多个订单
        'has_order' => array(
            'model' => 'order',
            'type' => HAS_MANY,
            'foreign_key' => 'buyer_id',
            'dependent' => true
        ),
        // 一个用户有多条收到的短信
        'has_received_message' => array(
            'model' => 'message',
            'type' => HAS_MANY,
            'foreign_key' => 'to_id',
            'dependent' => true
        ),
        // 一个用户有多条发送出去的短信
        'has_sent_message' => array(
            'model' => 'message',
            'type' => HAS_MANY,
            'foreign_key' => 'from_id',
            'dependent' => true
        ),
        // 会员和商品是多对多的关系（会员收藏商品）
        'collect_goods' => array(
            'model' => 'goods',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'collect',    //中间表名称
            'foreign_key' => 'user_id',
            'ext_limit' => array('type' => 'goods'),
            'reverse' => 'be_collect', //反向关系名称
        ),
        // 会员和店铺是多对多的关系（会员收藏店铺）
        'collect_store' => array(
            'model' => 'store',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'collect',
            'foreign_key' => 'user_id',
            'ext_limit' => array('type' => 'store'),
            'reverse' => 'be_collect',
        ),
        // 会员和店铺是多对多的关系（会员拥有店铺权限）
        'manage_store' => array(
            'model' => 'store',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'user_priv',
            'foreign_key' => 'user_id',
            'reverse' => 'be_manage',
        ),
        // 会员和好友是多对多的关系（会员拥有多个好友）
        'has_friend' => array(
            'model' => 'member',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'friend',
            'foreign_key' => 'owner_id',
            'reverse' => 'be_friend',
        ),
        // 好友是多对多的关系（会员拥有多个好友）
        'be_friend' => array(
            'model' => 'member',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'friend',
            'foreign_key' => 'friend_id',
            'reverse' => 'has_friend',
        ),
        //用户与商品咨询是一对多的关系，一个会员拥有多个商品咨询
        'user_question' => array(
            'model' => 'goodsqa',
            'type' => HAS_MANY,
            'foreign_key' => 'user_id',
        ),
        //会员和优惠券编号是多对多的关系
        'bind_couponsn' => array(
            'model' => 'couponsn',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'user_coupon',
            'foreign_key' => 'user_id',
            'reverse' => 'bind_user',
        ),
        // 会员和团购活动是多对多的关系（会员收藏商品）
        'join_groupbuy' => array(
            'model' => 'groupbuy',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'groupbuy_log',    //中间表名称
            'foreign_key' => 'user_id',
            'reverse' => 'be_join', //反向关系名称
        ),
        // 一个会员发起一个团购
        'start_groupbuy' => array(
            'model' => 'groupbuy',
            'type' => HAS_ONE,
            'foreign_key' => 'store_id',
            'dependent' => true
        ),
        // 一个会员拥有多个优惠码
        'has_couponsn' => array(
            'model' => 'couponsn',
            'type' => HAS_MANY,
            'foreign_key' => 'user_id',
            'dependent' => true
        ),
    );

    var $_autov = array(
        'user_name' => array(
            'required' => true,
            'filter' => 'trim',
        ),
        'password' => array(
            'required' => true,
            'filter' => 'trim',
            'min' => 6,
        ),
    );

    /*
     * 判断名称是否唯一
     */
    function unique($user_name, $user_id = 0)
    {
        $conditions = "user_name = '" . $user_name . "'";
        $user_id && $conditions .= " AND user_id <> '" . $user_id . "'";
        return count($this->find(array('conditions' => $conditions))) == 0;
    }

    function drop($conditions, $fields = 'portrait')
    {
        if ($droped_rows = parent::drop($conditions, $fields)) {
            restore_error_handler();
            $droped_data = $this->getDroppedData();
            foreach ($droped_data as $row) {
                $row['portrait'] && @unlink(ROOT_PATH . '/' . $row['portrait']);
            }
            reset_error_handler();
        }
        return $droped_rows;
    }


    /**
     * @author mingyang.sun
     * @date 2016-02-25
     * @param $ids
     *
     * @return mixed
     */
    public function getInByUserId($ids)
    {
        $sql = sprintf('SELECT * FROM %s WHERE `user_id` IN ( %s )', $this->table, implode(',', $ids));
        return $this->getAll($sql);
    }

    public function getSnum($user_id)
    {

        $sql = "SELECT COUNT(*) FROM " . DB_PREFIX_NEW . "show WHERE user_id={$user_id}";
        $snum = $this->getOne($sql);
        return $snum;
    }

    public function getShow($user_id)
    {

        $sql = "SELECT a.topic_id FROM heshe_showid_topic a LEFT JOIN heshe_show b ON a.show_id=b.show_id WHERE b.user_id={$user_id} GROUP BY a.topic_id";
        $data = $this->getAll($sql);
        $tnum = count((array)$data);
        return $tnum;
    }

    public function getlnum($user_id)
    {
        $sql = "SELECT COUNT(*) FROM herxi_collect WHERE user_id={$user_id} AND type='goods'";
        $lnum = $this->getOne($sql);
        return $lnum;
    }

    /**
     * 递增
     * @author    mingyang.sun
     * @date      2016-02-29
     * @param     $user_id
     * @param     $key
     * @param int $value
     *
     * @return bool
     */
    public function increment($user_id, $key, $value = 1)
    {
        $sql = sprintf('UPDATE %s SET `%s`=`%s` + %u WHERE `user_id`=%u', $this->table, $key, $key, $value, $user_id);
        return $this->query($sql);
    }

    /**
     * 递减
     * @author    mingyang.sun
     * @date      2016-02-29
     * @param     $user_id
     * @param     $key
     * @param int $value
     *
     * @return bool
     */
    public function decrement($user_id, $key, $value = 1)
    {
        $sql = sprintf('UPDATE %s SET `%s`=`%s` - %u WHERE `user_id`=%u AND `%s`>0', $this->table, $key, $key, $value, $user_id,$key);
        return $this->query($sql);
    }
    //生成验证码
    public function verifycode(){
        $width=180;
        $height=60;
        $number=4;
        $codestr ='';
        $font =ROOT_PATH .'/data/'."BRLNSDB.TTF";
        $font_size=25;
        //新建一个真彩色图像
        $img = imagecreatetruecolor($width,$height);
        //为一幅图像分配颜色
        $groundColor = imagecolorallocate($img,rand(0,156),rand(0,156),rand(0,156));
        imagefilledrectangle($img,0,0,$width,$height,$groundColor);
        for($i=0;$i<$number;$i++){
            $x = ($width/$number)*$i+10;
            $code=$this->getcode();
            $codestr .= $code;
            $codeColor = imagecolorallocate($img,rand(160,250),rand(160,250),rand(160,250));	//定义矩形颜色
            //用 TrueType 字体向图像写入文本
            imagettftext($img,$font_size,rand(-10,5),$x,$height/2+5,$codeColor,$font,$code);
        }
        //写入干扰元素
        $total = 100;
        for($i=0;$i<$total;$i++) {
            $noiceColor = imagecolorallocatealpha($img, 250, 250, 250, rand(80, 100));
            imagettftext($img, rand(5,10), 0, rand(1, $width), rand(1, $height), $noiceColor, $font, "*");
        }
        //线条
        for ($i=0;$i<6;$i++) {
            $color = imagecolorallocate($img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
            imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$color);
        }
        $data = array();
        $data['udid']=$_SERVER['HTTP_UDID'];
        $data['code']=$codestr;
        //存入redis
        import('redis.lib');
        $redis = new RedisDB(REDISHOST,REDISPWD);
        $result = $redis->setex($data['udid'],$data['code'],720);
        if($result){
            //header("Content-type:image/png");
            ob_start ();
            //imagepng($img);
            imagejpeg($img);
            $image_data = ob_get_contents ();
            ob_end_clean ();
            //dd('<img src="data:image/png;base64,' . base64_encode ($image_data) . '" />');
            return (base64_encode($image_data));
        }else{
            return false;
        }
    }
    protected function getcode(){
        $randStr = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $strlen = strlen($randStr)-1;
        return substr($randStr,rand(0,$strlen),1);
    }
}